package com.ideal.lx_mss.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ideal.lx_mss.common.ContractDictEntity;
import com.ideal.lx_mss.mapper.ContractDictMapper;
import com.ideal.lx_mss.service.ContractDictService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;


/**
 * 合同字典表
 */
@Service("contractDictService")
public class ContractDictServiceImpl extends ServiceImpl<ContractDictMapper, ContractDictEntity> implements ContractDictService {

    @Autowired
    private ContractDictMapper contractDictMapper;

    @Value("${spring.datasource.url}")
    private String databaseUrl;
    @Value("${spring.datasource.username}")
    private String userName;
    @Value("${spring.datasource.password}")
    private String passWord;

    /**
     * 查询字典
     * @param entity
     * @return
     */
    @Override
    public List<ContractDictEntity> getContractDictList(ContractDictEntity entity) {
        QueryWrapper<ContractDictEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("table_name",entity.getTableName());

        List<ContractDictEntity> contractDictEntities = contractDictMapper.selectList(queryWrapper);
        createContractTable(contractDictEntities,entity.getTableName());
        return contractDictEntities;


    }

    public void createContractTable(List<ContractDictEntity> list,String tableName){
        StringBuilder createTableSql = new StringBuilder("CREATE TABLE IF NOT EXISTS " + tableName + " (\n");
        ArrayList<Object> errList = new ArrayList<>();

        for (int i = 0; i < list.size(); i++) {

            String columnName = list.get(i).getColumnName();
            String datatype = list.get(i).getColumnType();
            String columnRemark =list.get(i).getColumnRemark();
            while (true){
                if (datatype.contains("character")){
                    int columnLen = Integer.parseInt(datatype.substring(datatype.indexOf("(") + 1, datatype.indexOf(")")));
                    if(columnLen>500){
                        createTableSql.append(columnName).append(" TEXT").append(" ").append("COMMENT").append("\""+columnRemark+"\"").append(",\n");
                        break;
                    }else {
                        createTableSql.append(columnName).append(" VARCHAR(").append(datatype.substring(datatype.indexOf("(")+1,datatype.indexOf(")"))).append(") ").append(" ").append("COMMENT").append("\""+columnRemark+"\"").append(",\n");
                        break;
                    }

                }
                if (datatype.contains("numeric")){
//                    createTableSql.append(columnName).append(" DECIMAL").append("(").append(datatype.substring(datatype.indexOf("(")+1,datatype.indexOf(")"))).append(")").append(" ").append("COMMENT").append("\""+columnRemark+"\"").append(",\n");
                    createTableSql.append(columnName).append(" DECIMAL").append(" ").append("(50,0)").append("COMMENT").append("\""+columnRemark+"\"").append(",\n");

                    break;
                }
                if ("date".equals(datatype)){
                    createTableSql.append(columnName).append(" datetime").append(" ").append("COMMENT").append("\""+columnRemark+"\"").append(",\n");
                    break;
                }
                if (datatype.contains("timestamp")){
                    createTableSql.append(columnName).append(" datetime").append(" ").append("COMMENT").append("\""+columnRemark+"\"").append(",\n");
                    break;
                }
                errList.add(datatype);

                break;
            }


        }

        int lastCommaIndex = createTableSql.lastIndexOf(",");
        createTableSql = new StringBuilder(createTableSql.substring(0, lastCommaIndex) + "\n");



        createTableSql.append(");");

        try {
            Connection conn = DriverManager.getConnection(databaseUrl, userName, passWord);
            Statement stmt = conn.createStatement();

            // 执行 SQL 创建表语句
            stmt.execute(createTableSql.toString());

            // 关闭连接
            stmt.close();
            conn.close();

            System.out.println("Table created successfully");

        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(createTableSql.toString());

    }

    public static void main(String[] args) {
        String str = "numeric(6,0)";

    }



}